package the.one.weather.ui.fragment;

import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.suke.widget.SwitchButton;

import java.util.List;

import butterknife.BindView;
import the.one.base.base.fragment.BaseFragment;
import the.one.base.base.presenter.BasePresenter;
import the.one.base.util.EventBusUtil;
import the.one.base.util.QMUIDialogUtil;
import the.one.location.TheLocationUtil;
import the.one.weather.R;
import the.one.weather.event.ChangedEvent;
import the.one.weather.model.Weather;
import the.one.weather.presenter.WeatherPresenter;
import the.one.weather.ui.adapter.CityAdapter;
import the.one.weather.util.LitePalUtil;
import the.one.weather.view.WeatherView;


//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛

/**
 * @author The one
 * @date 2019/5/7 0007
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
public class CityListFragment extends BaseFragment implements SwitchButton.OnCheckedChangeListener, AMapLocationListener, WeatherView {

    @BindView(R.id.recycle_view)
    RecyclerView mRecycleView;
    QMUIAlphaImageButton mAddBtn;

    private CityAdapter mAdapter;
    private List<Weather> weathers;
    private Weather closeLbs;
    private WeatherPresenter mPresenter;

    ImageView ivLll;
    AppCompatImageView ivWeather;
    LinearLayout llWeather;
    TextView tvCity;
    TextView tvWeather;
    TextView tvTemperature;
    ImageView ivLbs;

    AppCompatImageView ivDel;
    SwitchButton lbsSwitch;

    TheLocationUtil mLocationUtil;

    boolean isChanged = false;

    @Override
    protected boolean canDragBack() {
        return false;
    }

    @Override
    protected void initView(View rootView) {
        initFragmentBack("城市管理");
        mAddBtn = mTopLayout.addRightImageButton(R.drawable.mz_titlebar_add_dark, R.id.topbar_right_button1);
        mAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startFragment(new AddCityFragment());
            }
        });
        initRc();
        initLbs();
        initData();
    }

    private void initLbs() {
        View lbsLayout = getView(R.layout.item_city);
        ivLll = lbsLayout.findViewById(R.id.iv_lll);
        ivWeather = lbsLayout.findViewById(R.id.iv_weather);
        llWeather = lbsLayout.findViewById(R.id.ll_weather);
        tvCity = lbsLayout.findViewById(R.id.tv_city);
        tvWeather = lbsLayout.findViewById(R.id.tv_weather);
        tvTemperature = lbsLayout.findViewById(R.id.tv_temperature);
        ivLbs = lbsLayout.findViewById(R.id.iv_lbs);
        ivDel = lbsLayout.findViewById(R.id.iv_del);
        lbsSwitch = lbsLayout.findViewById(R.id.lbs_switch);
        lbsSwitch.setOnCheckedChangeListener(this);
        goneView(ivDel);
        showView(ivLbs);
        showView(lbsSwitch);
        ivLll.setVisibility(View.INVISIBLE);
        closeLbs = new Weather();
        closeLbs.setCurrentCity("自动定位");
        mAdapter.addHeaderView(lbsLayout);
        initLbsData(LitePalUtil.getLbsWeatherCity());
    }

    private void initLbsData(Weather weather) {
        if (weather != null) {
            lbsSwitch.setChecked(true);
            setLbsData(weather);
        } else {
            lbsSwitch.setChecked(false);
            setLbsData(closeLbs);
        }
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        isChanged = true;
        if (isChecked) {
            mLocationUtil = TheLocationUtil.getInstance().init(_mActivity, this);
            requestLbs();
        } else {
            LitePalUtil.deleteLbsWeatherCity();
            setLbsData(closeLbs);
        }
    }

    private void requestLbs() {
        showLoadingDialog("定位中");
        loadingDialog.setCanceledOnTouchOutside(false);
        mLocationUtil.startLocation();
    }

    private void setLbsData(Weather item) {
        ivWeather.setImageResource(item.getWeatherRes());
        tvCity.setText(item.getCurrentCity());
        if (TextUtils.isEmpty(item.getWeather())) {
            goneView(llWeather);
        } else {
            showView(llWeather);
            tvWeather.setText(item.getWeather());
            tvTemperature.setText(item.getTemperature());
            LitePalUtil.saveCityWeather(item);
        }
    }

    private void initData() {
        weathers = LitePalUtil.getNormalWeatherCities();
        if (null != weathers && weathers.size() != 0) {
            mAddBtn.setEnabled(weathers.size() < 9);
            mAdapter.setNewData(weathers);
        }
    }

    private void initRc() {
        mAdapter = new CityAdapter();
        ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
        itemTouchHelper.attachToRecyclerView(mRecycleView);

        // 开启拖拽
        mAdapter.enableDragItem(itemTouchHelper, R.id.iv_drag, false);
        mAdapter.setOnItemDragListener(onItemDragListener);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Weather weather = (Weather) adapter.getItem(position);
                weather.delete();
                isChanged = true;
                mAdapter.getData().remove(position);
                mAdapter.notifyDataSetChanged();
            }
        });

        mRecycleView.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecycleView.setAdapter(mAdapter);
    }

    OnItemDragListener onItemDragListener = new OnItemDragListener() {

        int startPosition;

        @Override
        public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
            startPosition = pos;
        }

        @Override
        public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
        }

        @Override
        public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int end) {
            if (startPosition != end) {
                // 初始移动位置的和最后不一样，说明移动过了
//                Weather startData = mAdapter.getData().get(startPosition);
//                Weather endData = mAdapter.getData().get(end);
//                long starTime = startData.getAddTime();
//                long endTime = endData.getAddTime();
//                startData.setAddTime(endTime);
//                endData.setAddTime(starTime);
//                startData.save();
//                endData.save();
                isChanged = true;
            }
        }
    };

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_city;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter = new WeatherPresenter();
    }

    @Override
    protected void onBackPressed() {
        if (isChanged) {
            List<Weather> weathers = mAdapter.getData();
            for (int i = 0; i < weathers.size(); i++) {
                Weather weather = weathers.get(i);
                weather.setAddTime(System.currentTimeMillis() + i * 100);
                weather.saveOrUpdate("id = ?", weather.getId() + "");
            }
        }
        // 检查是否至少有一个天气城市
        List<Weather> cities = LitePalUtil.getAllWeatherCities();
        if (null == cities || cities.size() == 0) {
            QMUIDialogUtil.showSimpleDialog(_mActivity, "提示", "至少选择一个城市");
            return;
        }
        if(isChanged){
            EventBusUtil.sendEvent(new ChangedEvent(cities));
        }
        super.onBackPressed();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        hideLoadingDialog();
        mLocationUtil.stopLocation();
        if (null == aMapLocation || TextUtils.isEmpty(aMapLocation.getDistrict())) {
            lbsSwitch.setChecked(false);
            showFailDialog("定位失败");
            return;
        }
        if (LitePalUtil.saveLbsCityWeather(aMapLocation.getDistrict()))
            mPresenter.getWeatherInfo(LitePalUtil.getLbsWeatherCity());
    }

    private void showFailDialog(String tips) {
        new QMUIDialog.MessageDialogBuilder(_mActivity)
                .setTitle("提示")
                .setMessage(tips)
                .addAction("关闭", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, "重新定位", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        requestLbs();
                    }
                })
                .setCanceledOnTouchOutside(false)
                .show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mLocationUtil)
            mLocationUtil.destroyLocation();
    }

    @Override
    public void onSuccess(Weather weather) {
        initLbsData(weather);
    }
}
